<?php

declare(strict_types=1);

namespace app\model;

use app\common\service\order\coupon_order\jutuike_channel\CouponOrderJutuikeBuild;
use app\model\base\BaseJtkGoodsModel;
use think\facade\Db;
use think\helper\Str;
use think\model\concern\SoftDelete;

/**
 *
 *
 * @mixin \think\Model
 * @property int $id
 * @property int $jtk_goods_id 聚推客产品id 即商品id
 * @property int $location_id 站点id
 * @property string $only_name 产品名称
 * @property string $product_title 产品主标题(前端给客户展示)
 * @property string $title 产品标题(管理后端展示)
 * @property string $face_img 封面图片
 * @property int $channel_sale_amount 渠道销量
 * @property int $is_sold_out 是否售罄，1：售罄，0未售罄
 * @property string $latitude 纬度
 * @property string $longitude 经度
 * @property string $city 站点名称
 * @property string $cityCode 城市编码
 * @property mixed $items 对应产品的套餐列表
 * @property mixed $shops 商家列表 所有经纬度采用 腾讯坐标系
 * @property string $category_name 产品分类名称
 * @property string $product_category_id 产品分类id
 * @property mixed $ext_data 拓展信息
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at 删除时间
 * @property int $order_show_id_card 是否需要填写身份证号 默认为0:否 默认过滤掉
 * @property int $booking_show_address 是否需要填写配送地址 默认为0:否 默认过滤掉
 * @property int $order_show_date 是否需要填写使用日期 默认为0:否 默认过滤掉
 * @property int $release_time 产品上线时间
 * @property-read string[] $category
 */
class JtkGoods extends BaseJtkGoodsModel
{

//    use SoftDelete;
    // tab选项
    const TAB_TYPE_NEW = 1;  // 最新上架
    const TAB_TYPE_DIS_SHORT = 2;  // 距离最近
    const TAB_TYPE_SALES_TOP = 3;  // 销量最高

    // 是否售罄，1：售罄，0未售罄
    const IS_SOLD_OUT_YES = 1; // 售罄
    const IS_SOLD_OUT_NO = 0; // 未售罄

    protected $json = ['items', 'shops', 'ext_data'];
    protected $hidden = ['items', 'shops', 'ext_data', 'title', 'cityCode'];

    public static $withSearch = [
        'product_id',
        'category_name', // 类名
        'tab_type', // tab选项类型
    ];

    /**
     * 分类关键词
     * @return string[]
     */
    public function getCategoryAttr() {
        $attr = [
            '火锅',
            '烤肉',
            '自助餐',
            '亲子',
            'KTV',
//            '电影',
            '酒店',
            '景区',
//            '体检',
//            '美容',
//            '洗牙',
            '生活',
        ];
        return $attr;
    }

    public static function findModel($productId) {
        $model = self::where('jtk_goods_id', $productId)->find();
        return $model;
    }

    // 产品id
    public function searchProductIdAttr($query, $value, $params) {
        if (isset($params['product_id'])) {
            $query->where('jktGoods.jtk_goods_id', $params['product_id']);
        }
    }

    // 分类
    public function searchCategoryNameAttr($query, $value, $params) {
        $categoryName = $params['category_name'] ?? '全部';
        if ($categoryName == '全部') {
            /**
             * 按类目分不准确

            $categoryId = [
                270 => '虚拟商品（周边游)',
//                271 => '文娱生活',
                272 => '民生充值',
                500 => '爱奇艺vip',
                501 => '优酷视频vip',
                502 => '腾讯视频vip',
                503 => 'QQ音乐vip',
                504 => '酷狗音乐vip',
                605 => '外卖会员',
                606 => '办公阅读类会员',
                607 => '音视频会员',
                636 => '视频会员',
                637 => '音频会员',
//                608 => '货币充值',
//                611 => '游戏类充值',
//                612 => '文娱类充值',
//                609 => '能源出行',
//                613 => '能源卡券',
//                614 => '出行卡券',
//                610 => '生活卡券',
//                615 => '商城卡券',
//                616 => '餐饮卡券',
//                508 => '社区团购类（勿选）',
//                509 => '社区团购类',
//                510 => '社区团购类',
            ];
            $query->whereNotIn('product_category_id', array_keys($categoryId));
             */

//            $query->where(function ($subQuery) {
//                collect($this->getCategoryAttr())->each(function ($name) use ($subQuery) {
//                    $subQuery->whereOr('only_name|product_title|category_name', 'like', '%' . $name . '%');
//                });
//            });

            $titleAttr = ["演出门票","话剧","小品","喜剧","医院","体检","美容养生", "SPA", "足疗",
                "按摩", "洗浴", "足道", "汗蒸", "中医", "推拿", "针灸", "护肤", "话费", "洁牙",
                "口腔", "保健", "医疗", "护理", "发货", "好物","包邮", "调理", "刮痧", "拔罐",
                "疗", "纹身", "电费", "话费", "同城配送", "VIP年卡", "VIP会员","会员年卡","会员极光年卡",
                "腾讯视频", "芒果TV", "爱奇艺","酒店","公寓","住宿","民宿","入住","别墅",
                "1晚","2晚", "大床房", "双人床",
                // 上面是聚推客分享的关键词
                "绿钻年卡", "音乐年卡", "天%晚", "纯玩%日游",
                ];

            $query->where(function ($subQuery) use ($titleAttr) {
                collect($titleAttr)->each(function ($name) use ($subQuery) {
                    $subQuery->where('title', 'not like', '%' . $name . '%');
                });

//                collect($titleAttr)->each(function ($name) use ($subQuery) {
//                    $subQuery->whereOr('title', 'not like', '%' . $name . '%');
//                });
            });

        } else {
            $query->whereLike('only_name|product_title|category_name', '%' . $categoryName . '%');
        }
    }

    // 选项卡类型
    public function searchTabTypeAttr($query, $value, $params) {
        $tabType = $params['tab_type'] ?? JtkGoods::TAB_TYPE_NEW;
        switch ($tabType) {
            case self::TAB_TYPE_NEW: // 最新上架
                $query->order('release_time desc');
                break;
            case self::TAB_TYPE_DIS_SHORT: // 距离最近
                $query->order('shopDis.min_dis');
                break;
            case self::TAB_TYPE_SALES_TOP: // 销量最高
                $query->order('channel_sale_amount desc');
                break;
            default:
                break;
        }
    }

    // ==================================== 业务逻辑 ==========================================
    /**
     * 商品列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function dataList($params) {
//        $latitude = '24.599707';
//        $longitude = '118.072318';

        $locationId = $params['location_id'];

        $query = self::query()
            ->withSearch(self::$withSearch, $params)
            ->where('location_id', $locationId)
            ->where('is_sold_out', self::IS_SOLD_OUT_NO)
            ->alias('jktGoods');



//        $time = date('Y-m-d', time()) . ' 00:00:00'; // 获取当前时间的时间戳
//        $timestamp = strtotime($time) * 1000; // 毫秒
//        // 抢购时间内
//        $query->where('begin_time', '>=', $timestamp);

        $latitude = $params['latitude'] ?? '';
        $longitude = $params['longitude'] ?? '';
        $shopDis = JtkGoodsShop::getDistanceQuery($locationId, $latitude, $longitude);
        $query->join([$shopDis=> 'shopDis'], 'shopDis.jtk_goods_id = jktGoods.jtk_goods_id', 'left');

//        halt($query->buildSql());

        $couponOrder = new CouponOrder();


        $list = $query
            ->paginate()
            ->each(function (JtkGoods $goodsModel) use ($couponOrder) {
                // 最划算的套餐，以下2种方式都可以
//                $items = collect($goodsModel->items)->order('salePrice')->shift();
                $cheapItems = collect($goodsModel->items)->order('salePrice')->first();
                $goodsModel->cheap_items = $cheapItems; // 最划算的套餐
                $salePrice = $cheapItems['salePrice'] ?? 0; // 销售价
                $originPrice = $cheapItems['originPrice'] ?? 0; // 成本价
                $goodsModel->min_sale_price = fen2yuan($salePrice); // 套餐里面最便宜的销售价
                $goodsModel->min_origin_price = fen2yuan($originPrice); // 套餐里面最便宜的销售价 对应的成本价

                // 佣金比例
                $couponOrder->params['goodsInfoList'] = $goodsModel;
                $buildService = new CouponOrderJutuikeBuild($couponOrder);
                $buildService->setParams($couponOrder->params);

                $goodsModel->commission_price = fen2yuan($buildService->profit);
//                $goodsModel->commission_price = fen2yuan($buildService->platform_profit);
                unset($buildService);
            })
            ->toArray();

        return $list;
    }


    /**
     * 批量保存聚推客数据
     * @param $jtkParams 二维数据
     * @return array
     * @throws \Exception
     */
    public function batchSaveDataJtk($jtkParams) {
        $result = ['status' => false, 'msg' => '保存失败'];
        if (empty($jtkParams)) {
            $result['msg'] = '保存失败，请求参数不能为空';
            return $result;
        }

        $columnsAttr = Db::getTableFields($this->table);
        $save = [];
        $saveShops = [];
        foreach ($jtkParams as $item) {
            $temp = [];
            foreach ($columnsAttr as $field) {
                $specialFieldAttr = ['id', 'deleted_at', 'created_at', 'updated_at']; // 不做处理的字段
                if (in_array($field, $specialFieldAttr)) {
                    continue;
                }
                switch ($field) {
                    case 'jtk_goods_id':
                        $temp[$field] = $item['id'];
                        break;
                    case 'ext_data':
                        $temp[$field] = $item;
                        break;
                    default:
                        $camelField = Str::camel($field); // 下划线转成驼峰
                        if (isset($item[$camelField])) {
                            $temp[$field] = $item[$camelField];
                        }
                        break;
                }

            }
            if ($temp) {
                $save[] = $temp;
            }

            // 门店 JtkGoodsShop
            if (!empty($item['shops'])) {
                foreach ($item['shops'] as $value) {
                    $saveShops[] = [
                        'jtk_goods_id' => $item['id'],
                        'location_id' => $item['locationId'],
                        'name' => $value['name'],
                        'latitude' => $value['latitude'],
                        'longitude' => $value['longitude'],
                    ];
                }
            } else {
                $saveShops[] = [
                    'jtk_goods_id' => $item['id'],
                    'location_id' => $item['locationId'],
                ];
            }

        }
        if (empty($save)) {
            $result['msg'] = '保存失败，没有数据可保存';
            return $result;
        }
        $model = new self();
        // saveAll方法新增数据返回的是包含新增模型（带自增ID）的数据集对象
        $res = $model->saveAll($save);
        if (empty($res)) {
            return $result;
        }

        $shopModel = new JtkGoodsShop();
        $shopModel->saveAll($saveShops);

        $result = ['status' => true, 'msg' => '保存成功'];
        return $result;
    }
}
